package com.hoshiicloud.fileserver.service.impl;

import com.hoshiicloud.common.exception.ServiceException;
import com.hoshiicloud.common.rpc.Response;
import com.hoshiicloud.fileserver.config.ObsConfig;
import com.hoshiicloud.fileserver.model.UploadFileResponse;
import com.hoshiicloud.fileserver.service.FileObjectService;
import com.hoshiicloud.fileserver.util.ObsUtil;
import com.obs.services.ObsClient;
import com.obs.services.exception.ObsException;
import com.obs.services.model.*;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.InputStream;

/**
 * 华为云obs文件对象操作服务接口类实现
 * 
 * @author Mr.wu
 *
 */
@Service
public class ObsFileObjectServiceImpl implements FileObjectService {

	private final static Logger logger = LoggerFactory.getLogger(ObsFileObjectServiceImpl.class);

	@Override
	public Response downloadFile(String bucketName, String objectKey) throws Exception {
		ObsClient obsClient=null;
		try {
			obsClient = ObsConfig.getDefaultObsClient();
			boolean exists = ObsUtil.bucketIsExists(bucketName);
			if (!exists) {
				return Response.failed("存储空间不存在");
			}
			ObsObject obsObject=obsClient.getObject(bucketName,objectKey);
			InputStream inputStream=obsObject.getObjectContent();
			return Response.data(inputStream);

		}catch (ObsException e) {
			// TODO: handle exception
			logger.error("下载失败，华为云服务出错：", e);
			return Response.failed("下载失败,华为云obs服务出错:"+e.getMessage());
		} catch (Exception e) {
			logger.error("下载失败：", e);
			return Response.failed("下载失败:"+e.getMessage());
			// TODO: handle exception
		}
		finally {
			//关闭连接
			if(obsClient!=null){
				obsClient.close();
			}
		}
	}

	@Override
	public Response<UploadFileResponse> uploadFile(String bucketName, String folder, String objectKey, InputStream fileStream) throws Exception {
		return uploadFile(bucketName, folder, objectKey, fileStream,false);
	}

	@Override
	public Response<UploadFileResponse> uploadFile(String bucketName, String folder, String objectKey, InputStream fileStream,Boolean privateOwned)
			throws Exception {
		ObsClient obsClient=null;
		try {
			obsClient = ObsConfig.getDefaultObsClient();
			boolean exists = ObsUtil.bucketIsExists(bucketName);
			if (!exists) {
				return Response.failed("存储空间不存在");
			}

			PutObjectResult result = null;
			//TODO 文件加密设置

			if (StringUtils.isNotBlank(folder)) {
				// 创建文件夹
				PutObjectRequest putObjectRequest=new PutObjectRequest();
				putObjectRequest.setBucketName(bucketName);
				putObjectRequest.setObjectKey(folder);
				result = obsClient.putObject(putObjectRequest);

				objectKey=folder + objectKey;
				//上传文件
				result = obsClient.putObject(bucketName,objectKey, fileStream);
			} else {
				result = obsClient.putObject(bucketName, objectKey, fileStream);
			}
			//因无设置权限的权限，暂不执行
			if(privateOwned && 1==2){
				//设置对象私有读写权限
				obsClient.setObjectAcl(bucketName,objectKey, AccessControlList.REST_CANNED_PRIVATE);
			}
			UploadFileResponse uploadFileRepsonse=new UploadFileResponse(200,"上传成功");
			uploadFileRepsonse.setObjectKey(objectKey);
			uploadFileRepsonse.setUrl(result.getObjectUrl());
			return Response.data(uploadFileRepsonse);
		} catch (ObsException e) {
			// TODO: handle exception
			logger.error("上传失败，华为云服务出错：", e);
			return Response.failed("上传失败,华为云obs服务出错:"+e.getMessage());
		} catch (Exception e) {
			logger.error("上传失败：", e);
			return Response.failed("上传失败:"+e.getMessage());
			// TODO: handle exception
		}
		finally {
			//关闭连接
			if(obsClient!=null){
				obsClient.close();
			}
		}

	}

	@Override
	public Response<String> test() {
		throw new ServiceException("存储空间不存在");
		//return Response.failed("存储空间不存在");
	}

	@Override
	public Response<String> deleteFile(String bucketName, String objectKey) throws Exception {
		ObsClient obsClient = null;
		try {
			obsClient = ObsConfig.getDefaultObsClient();
			boolean exists = ObsUtil.bucketIsExists(bucketName);
			if (!exists) {
				return Response.failed("存储空间不存在");
			}
			DeleteObjectResult result = null;
			result = obsClient.deleteObject(bucketName, objectKey);
			obsClient.close();
			return Response.success("删除成功");
		} catch (ObsException e) {
			logger.error("删除失败，华为云服务出错：", e);
			return Response.failed("删除失败,华为云obs服务出错:"+e.getMessage());
		} catch (Exception e) {
			logger.error("删除失败：", e);
			return Response.failed("删除失败:"+e.getMessage());
		}
		finally {
			if(obsClient!=null){
				obsClient.close();
			}
		}
	}

}
